package com.csc.dao;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;

import org.joda.time.DateTime;
import org.springframework.stereotype.Repository;

import com.csc.domain.SystemTimeUsed;

import constants.Constant;

@Repository
public class SystemTimeUsedDAOImpl implements SystemTimeUsedDAO {
	@PersistenceContext
	EntityManager em;

	/**
	 * @author Nguyen Vu Hung Insert SystemTimeUsed
	 */
	@Transactional
	public boolean addSystemTimeUsed(SystemTimeUsed sysTimeUsed) {
		boolean check = true;
		try {
			em.persist(sysTimeUsed);
		} catch (Exception e) {
			check = false;
		}
		return check;
	}

	public List<SystemTimeUsed> getAllListSystemTimeUsed() {
		DateTime currentDate = new DateTime();
	    DateTime date = currentDate.minusDays(3);
	    String strDate = date.toString(Constant.SIMPLE_DATE_FORMAT);
		TypedQuery<SystemTimeUsed> query = em.createQuery(
				"SELECT t FROM SystemTimeUsed t WHERE t.timeAction >='" + strDate +  "' ORDER BY t.timeAction DESC",
				SystemTimeUsed.class);
		return query.getResultList();
	}

	@Transactional
	public List<SystemTimeUsed> searchAdvance(String name, String role, String dateTo, String dateFrom) {
		String queryString = "SELECT s FROM SystemTimeUsed s WHERE "
				+ "s.sysAccount.accountLoginId like '%" + name +"%' AND "
				+ "s.sysAccount.systemAccountType.typeName like '%" + role +"%' AND "
				+ "(s.timeAction >= '" + dateFrom + "' AND "
				+ "s.timeAction <='"+ dateTo +"') ORDER BY s.timeAction DESC";
		TypedQuery<SystemTimeUsed> query = em.createQuery(queryString, SystemTimeUsed.class);
		return query.getResultList();
	}

	// If fromDate = null: get minimum date
	@Transactional
	public String getFromDate(String date) {
		if("".equals(date)) {
			Query query = em.createQuery("SELECT t.timeAction FROM SystemTimeUsed t ORDER BY t.timeAction ASC");
			query.setMaxResults(1);
			return query.getSingleResult().toString();
		}
		return date + " 00:00:00";
	}

	// If toDate = null: get current date
	@Transactional
	public String getToDate(String date) {
		if("".equals(date)) {
			Date now = new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat(
					Constant.SIMPLE_DATE_FORMAT);
			return dateFormat.format(now);
		}
		return date + " 23:59:59";
	}

}
